<template>
  <div class="blog-page" @keydown="handleKeydown" tabindex="0" ref="pageRef">
    <!-- 彩蛋提示 -->
    <EasterEggHint :show="showEasterEgg" />

    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="script-info">
          <h1 class="script-title">{{ script.name }}</h1>
          <div class="script-meta">
            <span class="script-filename">{{ script.fileName }}</span>
            <span class="script-size">{{ formatFileSize(script.fileSize) }}</span>
            <span class="script-date">{{ formatDate(script.createdTime) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 脚本内容 -->
    <div class="script-container">
      <a-spin :spinning="loading">
        <div class="script-content">
          <!-- 脚本信息卡片 -->
          <div class="script-info-card">
            <!-- 脚本描述 -->
            <div class="script-description" v-if="script.description">
              <h3 class="description-title">📝 脚本描述</h3>
              <p class="description-text">{{ script.description }}</p>
            </div>

            <!-- 脚本基本信息 -->
            <div class="script-basic-info">
              <h3 class="section-title">🔧 脚本信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <span class="info-label">文件名：</span>
                  <span class="info-value">{{ script.fileName }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">文件大小：</span>
                  <span class="info-value">{{ formatFileSize(script.fileSize) }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">状态：</span>
                  <span class="info-value status-badge" :class="script.status">
                    {{ script.status === 'active' ? '● 活跃' : '○ 维护中' }}
                  </span>
                </div>
              </div>
            </div>

            <!-- 支持系统 -->
            <div class="script-tags-section" v-if="systemsArray.length > 0">
              <h3 class="section-title">💻 支持系统</h3>
              <div class="tags-list">
                <a-tag v-for="system in systemsArray" :key="system" class="system-tag" color="green">
                  {{ system }}
                </a-tag>
              </div>
            </div>

            <!-- 功能特性 -->
            <div class="script-tags-section" v-if="featuresArray.length > 0">
              <h3 class="section-title">⚡ 功能特性</h3>
              <div class="tags-list">
                <a-tag v-for="feature in featuresArray" :key="feature" class="feature-tag" color="blue">
                  {{ feature }}
                </a-tag>
              </div>
            </div>

            <!-- 技术栈 -->
            <div class="script-tags-section" v-if="techStackArray.length > 0">
              <h3 class="section-title">🛠️ 技术栈</h3>
              <div class="tags-list">
                <a-tag v-for="tech in techStackArray" :key="tech" class="tech-tag" color="orange">
                  {{ tech }}
                </a-tag>
              </div>
            </div>
          </div>

          <!-- 脚本代码 -->
          <div class="script-code-section">
            <div class="terminal-bar">
              <div class="terminal-btns">
                <div class="terminal-btn red"></div>
                <div class="terminal-btn yellow"></div>
                <div class="terminal-btn green"></div>
              </div>
              <span class="terminal-title">{{ script.fileName }}</span>
              <div class="code-actions">
                <a-button type="text" size="small" @click="copyCode" class="copy-btn">
                  <span class="copy-icon">📋</span>
                  复制代码
                </a-button>
              </div>
            </div>
            <div class="code-content">
              <pre class="code-block"><code>{{ script.content }}</code></pre>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <a-empty v-if="!loading && !script.id" class="empty-state" description="脚本不存在">
          <template #image>
            <div class="empty-icon">🔧</div>
          </template>
          <template #description>
            <div>
              <h3>脚本不存在</h3>
              <p>该脚本可能已被删除或移动</p>
            </div>
          </template>
        </a-empty>
      </a-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, nextTick } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { message } from 'ant-design-vue';
  import { getPublicScriptDetail } from '/@/api/blog/scripts';
  import EasterEggHint from '../../components/EasterEggHint.vue';

  defineOptions({
    name: 'BlogScriptsDetailPage',
  });

  const route = useRoute();
  const router = useRouter();
  const pageRef = ref<HTMLElement>();
  const showEasterEgg = ref(false);
  const loading = ref(false);

  // 脚本数据
  const script = ref<any>({});

  // 解析JSON字符串
  const parseJsonArray = (jsonString: string): string[] => {
    try {
      if (!jsonString) {
        console.log('🔍 JSON字符串为空:', jsonString);
        return [];
      }
      console.log('🔍 解析JSON字符串:', jsonString);
      const result = JSON.parse(jsonString);
      console.log('✅ JSON解析结果:', result);
      return result;
    } catch (error) {
      console.error('❌ 解析JSON失败:', error, '原始字符串:', jsonString);
      return [];
    }
  };

  // 计算属性：解析后的数组
  const systemsArray = computed(() => {
    console.log('🔍 解析systems:', script.value.systems);
    return parseJsonArray(script.value.systems);
  });
  const featuresArray = computed(() => {
    console.log('🔍 解析features:', script.value.features);
    return parseJsonArray(script.value.features);
  });
  const techStackArray = computed(() => {
    console.log('🔍 解析techStack:', script.value.techStack);
    return parseJsonArray(script.value.techStack);
  });

  // 获取脚本详情
  const fetchScriptDetail = async () => {
    const scriptId = route.params.id;
    if (!scriptId) {
      message.error('脚本ID不存在');
      goBack();
      return;
    }

    loading.value = true;
    try {
      const res = await getPublicScriptDetail(scriptId as string);
      console.log('🔍 获取脚本详情:', res);

      if (res && res.id) {
        script.value = res;
        console.log('✅ 脚本数据设置成功:', script.value);
      } else {
        message.error('获取脚本详情失败');
        goBack();
      }
    } catch (error) {
      console.error('获取脚本详情失败:', error);
      message.error('获取脚本详情失败');
      goBack();
    } finally {
      loading.value = false;
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 复制代码
  const copyCode = async () => {
    try {
      await navigator.clipboard.writeText(script.value.content || '');
      message.success('代码已复制到剪贴板');
    } catch (error) {
      console.error('复制失败:', error);
      message.error('复制失败');
    }
  };

  // 键盘事件处理
  const handleKeydown = (event: KeyboardEvent) => {
    console.log('🔤 键盘事件触发:', event.key, event.target);

    if (event.key === 'ArrowLeft') {
      console.log('⬅️ 检测到左箭头键，准备返回');
      event.preventDefault();
      event.stopPropagation();
      goBack();
    }
  };

  // 返回上一页
  const goBack = () => {
    router.go(-1);
  };

  // 初始化
  onMounted(() => {
    fetchScriptDetail();

    // 设置页面焦点
    nextTick(() => {
      if (pageRef.value) {
        pageRef.value.focus();
      }
    });
  });
</script>

<style scoped lang="scss">
  @use '../../css/blog.scss' as *;

  /* 页面头部 */
  .page-header {
    margin-bottom: 2rem;
  }

  .header-content {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
  }

  .script-info {
    text-align: center;
  }

  .script-title {
    font-size: 2.5rem;
    font-weight: 700;
    color: white;
    margin: 0 0 1rem 0;
    line-height: 1.3;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  .script-meta {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1.5rem;
    color: rgba(255, 255, 255, 0.8);
    font-size: 1rem;
    font-weight: 500;
  }

  .script-filename {
    background: linear-gradient(135deg, #52c41a, #1890ff);
    color: white;
    padding: 0.4rem 1rem;
    border-radius: 20px;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  }

  /* 脚本内容 */
  .script-container {
    max-width: 1000px;
    margin: 0 auto;
  }

  .script-content {
    display: flex;
    flex-direction: column;
    gap: 2rem;
  }

  .script-info-card {
    background: linear-gradient(135deg, rgba(40, 44, 52, 0.95) 60%, rgba(24, 144, 255, 0.10) 100%);
    backdrop-filter: blur(24px);
    border-radius: 22px;
    border: 1.5px solid rgba(255, 255, 255, 0.13);
    padding: 2.5rem 2rem 2rem 2rem;
    box-shadow: 0 12px 40px 0 rgba(24, 144, 255, 0.10), 0 2px 8px 0 rgba(0,0,0,0.10);
    margin-bottom: 2.5rem;
    transition: box-shadow 0.3s cubic-bezier(.4,0,.2,1), transform 0.3s cubic-bezier(.4,0,.2,1);
    animation: fadeInUp 0.7s cubic-bezier(.4,0,.2,1);
  }

  @keyframes fadeInUp {
    from { opacity: 0; transform: translateY(30px); }
    to { opacity: 1; transform: translateY(0); }
  }

  .script-description {
    margin-bottom: 2.2rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  }

  .description-title {
    font-size: 1.35rem;
    font-weight: 700;
    color: #fff;
    margin: 0 0 1rem 0;
    letter-spacing: 1px;
  }

  .description-text {
    color: rgba(255, 255, 255, 0.93);
    line-height: 1.7;
    font-size: 1.05rem;
    margin: 0;
    letter-spacing: 0.2px;
  }

  .script-basic-info {
    margin-bottom: 2.2rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  }

  .section-title {
    font-size: 1.18rem;
    font-weight: 600;
    color: #fff;
    margin: 0 0 1.1rem 0;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    border: none;
    letter-spacing: 0.5px;
  }

  .section-title::after,
  .section-title::before {
    display: none !important;
    content: none !important;
  }

  .info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 1.1rem;
  }

  .info-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.6rem 0.7rem;
    background: rgba(255, 255, 255, 0.04);
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.08);
    font-size: 1rem;
    transition: box-shadow 0.2s, background 0.2s;
  }

  .info-item:hover {
    background: rgba(24, 144, 255, 0.10);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.10);
  }

  .info-label {
    color: rgba(255, 255, 255, 0.7);
    font-weight: 500;
    min-width: 80px;
    font-size: 0.97rem;
  }

  .info-value {
    color: #fff;
    font-weight: 700;
    font-size: 1.01rem;
  }

  .status-badge {
    padding: 0.22rem 0.7rem;
    border-radius: 13px;
    font-size: 0.92rem;
    font-weight: 700;
    letter-spacing: 0.5px;
    background: rgba(82, 196, 26, 0.13);
    color: #52c41a;
    border: 1px solid rgba(82, 196, 26, 0.18);
    transition: background 0.2s, color 0.2s;
  }

  .status-badge.maintenance {
    background: rgba(250, 173, 20, 0.13);
    color: #faad14;
    border: 1px solid rgba(250, 173, 20, 0.18);
  }

  .script-tags-section {
    margin-bottom: 1.7rem;
  }

  .script-tags-section:last-child {
    margin-bottom: 0;
  }

  .tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  .system-tag,
  .feature-tag,
  .tech-tag {
    margin: 0;
    padding: 0.38rem 0.95rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.93rem;
    backdrop-filter: blur(10px);
    border: 1.2px solid rgba(255, 255, 255, 0.18);
    background: rgba(24, 144, 255, 0.10);
    color: #fff;
    transition: transform 0.18s, box-shadow 0.18s, background 0.18s;
    cursor: pointer;
  }

  .system-tag:hover,
  .feature-tag:hover,
  .tech-tag:hover {
    transform: scale(1.08);
    background: rgba(24, 144, 255, 0.18);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.13);
  }

  /* 代码区美化 */
  .script-code-section {
    margin-top: 2.5rem;
    background: #23272e;
    border-radius: 14px;
    box-shadow: 0 4px 24px rgba(24, 144, 255, 0.08), 0 1.5px 8px rgba(0,0,0,0.18) inset;
    padding: 0 0 1.2rem 0;
    position: relative;
    overflow: hidden;
    border: 1.2px solid #23272e;
    animation: fadeInUp 0.7s cubic-bezier(.4,0,.2,1);
    min-height: 220px;
  }

  .terminal-bar {
    display: flex;
    align-items: center;
    height: 36px;
    background: linear-gradient(90deg, #23272e 80%, #181c20 100%);
    border-bottom: 1px solid #22252b;
    padding: 0 1.2rem;
    position: relative;
  }

  .terminal-btns {
    display: flex;
    gap: 0.5rem;
  }

  .terminal-btn {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 0.3rem;
    display: inline-block;
    border: 1.5px solid rgba(0,0,0,0.08);
  }

  .terminal-btn.red { background: #ff5f56; border-color: #e0443e; }
  .terminal-btn.yellow { background: #ffbd2e; border-color: #dea123; }
  .terminal-btn.green { background: #27c93f; border-color: #13a10e; }

  .terminal-title {
    flex: 1;
    text-align: center;
    color: #bfc9d1;
    font-size: 1.02rem;
    font-weight: 600;
    letter-spacing: 0.2px;
    font-family: 'Fira Mono', 'Consolas', 'Menlo', monospace;
    user-select: text;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .code-actions {
    position: absolute;
    right: 1.2rem;
    top: 0;
    height: 36px;
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .copy-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 28px;
    min-width: 100px;
    padding: 0 1.1rem;
    color: #18a0ff;
    background: rgba(24, 144, 255, 0.08);
    border-radius: 8px;
    border: none;
    font-weight: 600;
    font-size: 0.92rem;
    transition: background 0.2s, color 0.2s, transform 0.18s;
    box-shadow: none;
    line-height: 1;
    letter-spacing: 0.5px;
  }

  .copy-btn .copy-icon {
    font-size: 1.1rem;
    margin-right: 0.4em;
    display: flex;
    align-items: center;
  }

  .copy-btn:hover {
    background: #18a0ff;
    color: #fff;
    transform: scale(1.08);
  }

  .code-content {
    background: transparent;
    border-radius: 0 0 10px 10px;
    padding: 1.1rem 1.2rem 1rem 1.2rem;
    overflow-x: auto;
    font-size: 1.08rem;
    font-family: 'Fira Mono', 'Consolas', 'Menlo', monospace;
    color: #e6eaea;
    line-height: 1.7;
    box-shadow: none;
    min-height: 120px;
  }

  .code-block {
    margin: 0;
    background: none;
    border: none;
    padding: 0;
    color: inherit;
    font-size: inherit;
    font-family: inherit;
    white-space: pre;
  }

  /* 滚动条终端风格 */
  .code-content::-webkit-scrollbar {
    height: 8px;
    background: #23272e;
  }

  .code-content::-webkit-scrollbar-thumb {
    background: #181c20;
    border-radius: 8px;
  }

  /* 响应式优化 */
  @media (max-width: 1024px) {
    .script-code-section {
      padding: 0 0 0.7rem 0;
    }
    .code-content {
      padding: 0.7rem 0.5rem 0.5rem 0.5rem;
    }
  }
  @media (max-width: 768px) {
    .script-code-section {
      padding: 0 0 0.5rem 0;
    }
    .code-content {
      font-size: 0.95rem;
      padding: 0.5rem 0.2rem 0.3rem 0.2rem;
    }
    .copy-btn {
      font-size: 0.88rem;
      min-width: 80px;
      padding: 0 0.8rem;
    }
    .code-actions {
      right: 0.5rem;
    }
  }

  .code-with-linenum {
    display: flex;
    flex-direction: row;
    align-items: stretch;
    position: relative;
    overflow-x: auto;
    overflow-y: auto;
    max-height: 60vh;
  }
  .code-linenum-col {
    user-select: none;
    background: #20242a;
    color: #5c6370;
    text-align: right;
    padding: 1.1rem 0.7rem 1rem 0.7rem;
    font-family: 'Fira Mono', 'Consolas', 'Menlo', monospace;
    font-size: 1.08rem;
    border-radius: 0 0 0 10px;
    min-width: 2.5em;
    line-height: 1.7;
    border-right: 1px solid #23272e;
    height: 100%;
    box-sizing: border-box;
    flex-shrink: 0;
  }
  .code-linenum {
    display: block;
    height: 1.7em;
    line-height: 1.7em;
    padding-right: 0.3em;
  }
  .code-main {
    flex: 1;
    background: transparent;
    margin: 0;
    padding: 0 0 0 0.5em;
    color: inherit;
    font-size: inherit;
    font-family: inherit;
    white-space: pre;
    overflow-x: auto;
    height: 100%;
    box-sizing: border-box;
  }

  /* 滚动条终端风格 */
  .code-content::-webkit-scrollbar {
    height: 8px;
    background: #23272e;
  }

  .code-content::-webkit-scrollbar-thumb {
    background: #181c20;
    border-radius: 8px;
  }

  /* 响应式优化 */
  @media (max-width: 1024px) {
    .code-linenum-col {
      font-size: 0.95rem;
      padding: 0.7rem 0.5rem 0.5rem 0.5rem;
    }
  }
  @media (max-width: 768px) {
    .code-linenum-col {
      font-size: 0.85rem;
      padding: 0.5rem 0.3rem 0.3rem 0.3rem;
    }
  }
</style>
